<?php
namespace app\api\controller;

use app\api\model\AdminUser;
use app\api\model\Role as RoleModel;
use app\api\model\RoleAccess;
use app\api\model\UserRole;
use think\facade\Db;
use think\facade\Request;

class Role extends ApiBase
{
    public function getRoleList(\think\Request $request){
        /*查询自己所属角色，不能操作自己所属角色*/
        $username=$request->token_user_name;
        $id = AdminUser::where('username',$username)->value('id');
        $role_id = UserRole::where('admin_user_id',$id)->column('role_id');
        $list = RoleModel::whereNotIn('id',$role_id)->select()->toArray();
//        $list = RoleModel::select()->toArray();
        return renderSuccess('',$list);

    }

    public function getRoleById(){
        $data = Request::post();

        if(!isset($data['id'])) return  renderError('缺少参数');
        $role = RoleModel::find($data['id']);
        $access = $role->access->hidden(['pivot'])->toArray();
        $ids = [];
        foreach ($access as $k=>$v){
            $ids[]=$v['id'];
        }
        /*获取叶子节点*/
        $tree = getTree($access,0);
        $leaf = $this->getLeaf($tree);
        $res = [
           'name'=>$role['name'],
           'sort'=>$role['sort'],
           'access'=>$ids,
           'leaf'=>$leaf
        ];
        return renderSuccess('',$res);

    }

    public function getLeaf($tree){
        $data = [];
        foreach ($tree as $k=>$v){
            if(isset($v['children'])){
               $res = $this->getLeaf($v['children']);
               $data = array_merge($data,$res);
            }else{
               $data[] = $v['id'];
            }
        }
        return $data;
    }

    public function add(){
        $data = Request::post();

        $time = strtotime('now');
        $roleData = [
            'name'=>$data['name'],
            'sort'=>$data['sort'],
            'create_time'=>$time
        ];

        Db::startTrans();
        try {
            $role = RoleModel::create($roleData);
            $role->access()->save($data['access']);
            // 提交事务
            Db::commit();
            return renderSuccess('添加成功');
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return renderError($e->getMessage());
        }
    }

    public function edit(){
        $data = Request::post();
        $time = strtotime('now');
        $roleData = [
            'id'=>$data['id'],
            'name'=>$data['name'],
            'sort'=>$data['sort'],
            'update_time'=>$time
        ];

        Db::startTrans();
        try {
            $role = RoleModel::update($roleData);
            $del = RoleAccess::where('role_id',$data['id'])->delete();
            $role->access()->save($data['access']);
            // 提交事务
            Db::commit();
            return renderSuccess('更新成功');
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return renderError($e->getMessage());
        }

    }
}